<?php

namespace app\api\services;

use app\common\libs\Singleton;
use app\common\models\Member\MemberRechargeOrder;
use app\common\models\Order\OrderPay;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Log;

class RechargeService
{
    use Singleton;

    /**
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function payCallback($orderNo): bool
    {
        $payInfo = OrderPay::getInstance()->where('order_no', $orderNo)->find();
        if (empty($payInfo)) {
            return false;
        }

        $order = MemberRechargeOrder::getInstance()->where('order_no', $orderNo)->find();
        if (empty($order)) {
            return false;
        }

        if ($order['status'] == 1) {
            return false;
        }

        try {
            $orderData = [
                'status' => 1,
                'pay_at' => date('Y-m-d H:i:s'),
            ];

            //更新
            MemberRechargeOrder::getInstance()->where('order_no', $orderNo)->update($orderData);

            $msg = '余额充值，订单' . $orderNo;
            MemberService::getInstance()->addFinanceLog($payInfo['userId'], 'recharge', $payInfo['payPrice'], 1, $msg, $payInfo['orderNo']);

        } catch (\Exception $e) {
            Log::error($e->getMessage());
            return false;
        }
        return true;
    }
}